<?php
class Defined_Authenticate{
	
	function __construct(){
	}
	
	public function login($username, $password){
		if(trim($username)=='' || trim($password)=='')
			return false;
		$auth = Zend_Auth::getInstance();
	    $authAdapter=new Zend_Auth_Adapter_DbTable(
			Zend_Registry::get('db'),
			'users',
			'email',
			'password'
           
		);
	    $authAdapter->setIdentity($username);
	    $authAdapter->setCredential($password);
	    $result=$auth->authenticate($authAdapter);
        
	    if($result->isValid()){
	    	$storage=$auth->getStorage();
	    	$arrUser=$authAdapter->getResultRowObject();
	    	//$arrUser['user_type']=$user_type;
	    	$storage->write($arrUser);
	    	return true;
	    }
	    return $result;
	}

	public function logout(){
		$auth=Zend_Auth::getInstance();
		$storage=$auth->getStorage();
		$storage->clear();
		$auth->clearIdentity();	 
	}
	
	function isLogged(){
		$author=$this->getAuthorization();
		$result=true;
		if(!isset($author)) $result=false;
		if(!$author) $result=false;
		unset($author);
		return $result;
	}
	
	function getIdentity(){
		$auth = Zend_Auth::getInstance();
	    if ($auth->hasIdentity()) {
          return $auth->getIdentity();
        }
        return false;
	}
	
	function getAuthorization(){
    	$auth=Zend_Auth::getInstance();
    	$storage=$auth->getStorage();
    	$data=$storage->read();
    	unset($storage,$auth);
		return $data;
	}
	
	/**
	 * make sure a user is loged or not
	 *
	 * @param string $sRedirect
	 * @param boolean $bMustLogin (true: force login, if not loged, we redirect - false: force no login, if loged, we redirect)
	 * @return void or return array
	 */
	
	function checkLogin($sRedirect='/', $bMustLogin=true){
  		$auth = Zend_Auth::getInstance();
  		if($bMustLogin){
	    	if($this->isLogged()===true){	
	    		$check = $auth->getIdentity();
	    		$data=$check;
	    		unset($check); unset($bMustLogin); unset($auth); unset($sRedirect);
	    		return $data;
			}else {
				unset($auth); unset($bMustLogin);
				header("Location: $sRedirect");
				exit();
			}
  		}else{
	    	if($this->isLogged()===true){
				unset($auth); unset($bMustLogin);
				header("Location: $sRedirect");
				exit();
	    	}
  			
  		}
		unset($auth);unset($sRedirect); unset($bMustLogin);
	}
	
	function __destruct(){
	}
}


?>